package cz.vargagab.server;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

import cz.vargagab.domain.ClientRmiNode;
import cz.vargagab.repo.ExternalServerService;
import cz.vargagab.repo.InternalClientService;

/**
 * http://www.java-tips.org/java-ee-tips/java-servlet/how-to-work-with-servletcontextlistener.html
 * @author Gabriel Varga
 *
 */
public  class MyListener implements ServletContextListener {

  
  private ServletContext context = null;

  /*This method is invoked when the Web Application has been removed 
  and is no longer able to accept requests
  */

  public void contextDestroyed(ServletContextEvent event)
  {
//	  @Autowired
//	  ClientRmiNode thisNode;
    //Nemozno pouzit @Autowired, pretoze MyListener neni Springova beana. Zavislosti mozno dostat do kodu vdaka helperu WebApplicationContextUtils
    this.context = null;
    ClientRmiNode thisNode =  (ClientRmiNode) WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean("thisNode");
    System.out.println("RMI Node "+thisNode.getName() +" Has Been Removed");
    ExternalServerService  externalServerServiceRmi = (ExternalServerService)  WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean("nodeServiceRmi");
    InternalClientService internalClientService = (InternalClientService) WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean("internalClientService");
    
    if (internalClientService.isLoggedIn() )
    	{
    		externalServerServiceRmi.logout(thisNode);
    	}
  }
  //This method is invoked when the Web Application
  //is ready to service requests

  public void contextInitialized(ServletContextEvent event)
  {
    System.out.println("RMI Node Is Ready");
  }
}